<?php

class Db
{
  private $host = 'zbytocnosti.sk';
  private $db_name = 'zbytocnosti_sk_vlcak';
  private $user = 'vlcak';
  private $pass = 'sugUp2aS-6431';
  
  // SINGLETON STUFF START
  private static $instance = NULL;
  
  private function __construct() 
  {
  }
  
  public function getInstance()
  {
    static $instance;
    if(!isset($instance))
    {
      $instance = new self();
    }
    return $instance;
  }
  
  public function __clone()
  {
    trigger_error('Clone is not allowed.', E_USER_ERROR);
  }
  //SINGLETON STUFF END
  
  public static function init()
  {
    $db = self::getInstance();
    $db->link = mysql_connect($db->host,$db->user,$db->pass);
    if(!$db->link)
    {
      die('Could not connect: ' . mysql_error());
    }
    mysql_select_db($db->db_name);
    mysql_query("set names 'utf8'");
  }
  
  public static function close()
  {
    $db = self::getInstance();
    mysql_close($db->link);
    
  }
  
  public static function query($query)
  {
    $db = self::getInstance();
    mysql_query($query);
  }
  
  public static function fetchAll($select)
  {
    $db = self::getInstance();
    $result = mysql_query($select);
    if(!$result)
    {
      die("Could not successfully run query ($select) from DB: " . mysql_error());
    }
    if(mysql_num_rows($result) == 0)
    {
      return array();
    }
    $array = array();
    while($row = mysql_fetch_assoc($result))
    {
      $array []= $row;
    }
    return $array;
  }
  
  public static function fetchRow($select)
  {
    $array = self::fetchAll($select);
    if(count($array)<1)
    {
      throw new Exception("Fetch row: no such row ($select): " . mysql_error());
    }
    return $array[0];
  }
}
